package cn.eric.framework.ajax;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class EContextAdvice implements MethodInterceptor {
    private static final int PAGE_SIZE_ALL = -1;

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Object[] args = methodInvocation.getArguments();
        int currentPage;
        int pageSize;
        boolean isAll = false;
        for (Object o : args) {
            if (o.getClass().equals(EricContext.class)) {
                currentPage = ((EricContext) o).getCurrentPage();
                pageSize = ((EricContext) o).getRowPerPage();
                isAll = pageSize == PAGE_SIZE_ALL;
                if (isAll) {
                    ((EricContext) o).setCurrentPage(0);
                } else {
                    ((EricContext) o).setCurrentPage(currentPage == 0 ? 0 : currentPage - 1);
                }
            }
        }

        if (isAll) {
            EricContextInnerResponse responseWith1 = (EricContextInnerResponse) methodInvocation.getMethod().invoke(methodInvocation.getThis(), args);
            for (Object o : args) {
                if (o.getClass().equals(EricContext.class)) {
                    ((EricContext) o).setCurrentPage(0);
                    ((EricContext) o).setRowPerPage(responseWith1.getContext().getTotalPage() * responseWith1.getContext().getRowPerPage() + 1);
                    return methodInvocation.getMethod().invoke(methodInvocation.getThis(), args);
                }
            }
            return null;
        } else {
            return methodInvocation.getMethod().invoke(methodInvocation.getThis(), args);
        }
    }
}
